local Msg = require("core.Msg")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local HechengConfig = require("excel.Hecheng")
local Grid = require("bag.Grid")
local ObjHuman = require("core.ObjHuman")
local Log = require("common.Log")
local TaskCallbacks = require("task.TaskCallbacks")
local TaskDefine = require("task.Define")

function hecheng(human, index, cnt)
  local config = HechengConfig.hecheng[index]
  if not config or cnt < 0 then
    assert(nil, index, cnt)
    return
  end
  if human.db.lv < config.lv then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_HECHENG_LV_NOT_ENOUGH)
  end
  for i=1, #config.needItem do
    if BagLogic.getItemCount(human, config.needItem[i][1]) < config.needItem[i][2] * cnt then
      return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_HECHENG_ITEM_NOT_ENOUGH)
    end
  end
  if not BagLogic.checkCanAddItem(human, config.id, config.bind, cnt) then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_BAG_GRID_NOT_ENOUGH)
  end
  if ObjHuman.getYinliang(human) < config.needYL then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_YINLIANG_NOT_ENOUGH)
  end
  if ObjHuman.getBindYuanbao(human) < config.needBindYuanbao then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_BIND_YUANBAO_NOT_ENOUGH)
  end
  for i=1, #config.needItem do
    BagLogic.delItemsById(human, config.needItem[i][1], config.needItem[i][2] * cnt, "hecheng")
  end
  ObjHuman.decBindYuanbao(human, config.needBindYuanbao * cnt, "hecheng")
  ObjHuman.decYinliang(human, config.needYL * cnt, "hecheng")  
  BagLogic.addItem(human, config.id, config.bind, cnt, "hecheng")
  Broadcast.sendBroadcast(human, Lang.DOWN, Lang.REFINE_HECHENG_SUCCESS)
  TaskCallbacks.taskRefineCB(human, TaskDefine.TASK_REFINE_HC)  
  Log.write(Log.LOGID_OSS_HECHENG, human._id,human.account,human.name,human.db.lv, config.id, cnt)
end


function getConfig(human)
  local cache = {}  
  local sendMsg = Msg.gc.GC_GET_HECHENG_CONFIG
  for i=1,#HechengConfig.hecheng do
    Grid.create(cache, HechengConfig.hecheng[i].id, 1)
    Grid.makeItem(cache, sendMsg.info[i].hcItem, 0, human)
    sendMsg.info[i].type = HechengConfig.hecheng[i].type
    sendMsg.info[i].needYinliang = HechengConfig.hecheng[i].needYL
    sendMsg.info[i].needBindYuanbao = HechengConfig.hecheng[i].needBindYuanbao
    sendMsg.info[i].needLv = HechengConfig.hecheng[i].lv
    sendMsg.info[i].needItem[0] = #HechengConfig.hecheng[i].needItem
    for j=1, #HechengConfig.hecheng[i].needItem do
      Grid.create(cache, HechengConfig.hecheng[i].needItem[j][1],HechengConfig.hecheng[i].needItem[j][2])
      Grid.makeItem(cache, sendMsg.info[i].needItem[j], 0, human)
    end
    sendMsg.info[i].needItem[0] = #HechengConfig.hecheng[i].needItem
  end
  sendMsg.info[0] = #HechengConfig.hecheng
  Msg.send(sendMsg, human.fd)
end